package logic

import (
	"context"
	"github.com/google/uuid"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"major-six/major/order/internal/models"
	"time"

	"major-six/major/order/internal/svc"
	"major-six/major/order/order"

	"github.com/zeromicro/go-zero/core/logx"
)

type OrderAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewOrderAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OrderAddLogic {
	return &OrderAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *OrderAddLogic) OrderAdd(in *order.OrderAddRequest) (*order.OrderAddResponse, error) {
	mod := models.NewOrderModel(l.ctx, l.svcCtx)
	gmod := models.NewGoodsModel(l.ctx, l.svcCtx)
	goodsInfo, err := gmod.GoodsInfo(int(in.GoodsId))
	if err != nil {
		return nil, err
	}
	if goodsInfo.GoodsStock-1 < 0 {
		return nil, status.Error(codes.DeadlineExceeded, "库存不足")
	}

	no := uuid.NewString()
	count := float32(goodsInfo.GoodsNum) * goodsInfo.GoodsPrice
	format := time.Now().Format("2006-01-02 15:04:05")

	orderInfo := models.Order{
		GoodsId:     int(in.GoodsId),
		OrderNo:     no,
		OrderCount:  float64(count),
		OrderStatus: 0,
		CreatedAt:   format,
	}

	create, err := mod.Create(orderInfo)
	if err != nil {
		return nil, err
	}
	return &order.OrderAddResponse{AddOrder: create}, nil
}
